package com.example.capsule_chat0322.netty;

import com.example.capsule_chat0322.bean.MessageBean;

import com.example.capsule_chat0322.interfaces.NettyMessageInterface;
import com.example.capsule_chat0322.listener.NettyGroupMessageListener;
import com.example.capsule_chat0322.listener.NettyOneToOneMessageListener;
import com.example.capsule_chat0322.protocol.MessageBeanProtocol;
import com.google.gson.Gson;

import java.nio.charset.StandardCharsets;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;

public class ClientNettyHandler extends SimpleChannelInboundHandler<MessageBeanProtocol> {

    private NettyMessageInterface nettyMessageInterface;

    public ClientNettyHandler(NettyMessageInterface nettyMessageInterface) {
        this.nettyMessageInterface = nettyMessageInterface;
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

    }

//    @Override
//    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//        nettyMessageInterface.consumerMessage(msg);
//    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageBeanProtocol msg) throws Exception {


        byte[] content = msg.getContent();
        String message = new String(content, StandardCharsets.UTF_8);
        MessageBean messageBean = new Gson().fromJson(message, MessageBean.class);

        if (messageBean.isOneToOne()) {
            nettyMessageInterface = new NettyOneToOneMessageListener();
        } else {
            nettyMessageInterface = new NettyGroupMessageListener();
        }

        nettyMessageInterface.consumerMessage(messageBean);

    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {

        if (evt instanceof IdleStateEvent) {
            MessageBean messageBean = new MessageBean();
            messageBean.setSenderId(String.valueOf(-10000));
            MessageBeanProtocol messageBeanProtocol = new MessageBeanProtocol();
            String messageJson = new Gson().toJson(messageBean);
            messageBeanProtocol.setLen(messageJson.getBytes(StandardCharsets.UTF_8).length);
            messageBeanProtocol.setContent(messageJson.getBytes(StandardCharsets.UTF_8));
            ctx.channel().writeAndFlush(messageBeanProtocol);
        }

    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {

    }

}
